
import 'dart:async';

import 'package:car/util/toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import '../entity/book_entity.dart';
import '../event/inventory_event.dart';
import '../http/api.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/analysis_book_rule.dart';

class Up extends StatefulWidget {
  const Up({Key? key}) : super(key: key);

  @override
  State<Up> createState() => _UpState();
}

class _UpState extends State<Up> {

  RxnString floor = RxnString();
  String? placeNo;
  RxInt count = RxInt(0);
  RxList<BookEntity> bookList = RxList();
  RxBool hasUp = RxBool(false);

  RxInt step = 1.obs;

  StreamSubscription? subscription;

  @override
  initState() {
    super.initState();
    subscription = eventFactory.on<InventoryEvent>().listen((event) {
      print('epc = ${event.data}');
      di.play('audio/di.wav');

      _analyze(event.data);
    });
    // uhfSerialPortHelper.sendData(start());

    player.play('audio/scan_place.mp3');
  }

  @override
  void dispose() {
    subscription?.cancel();
    subscription = null;
    super.dispose();
  }

  _analyze(String epc){
    if(placeNo == null){
      if(epc.startsWith('B0')){
        try{
          var length = int.parse(epc.substring(2,4));
          placeNo = epc.substring(4,4+length);
          _findPlace(placeNo);
          return;
        }catch(e){
          print(e);
        }
      }
    }else{
      if(!epc.startsWith('B0')){
        try{
          var no = analysisBookNoRule(epc);
          if(no == null || no.isEmpty){
            toastWarn('条码号解析失败');
            return;
          }
          if(!bookList.map((element) => element.no).contains(no) && no.isNotEmpty){
            bookList.add(BookEntity()..no = no);
            _findBook(no);
          }
        }catch(e){
          print(e);
        }
      }
    }
  }

  _findPlace(no) async {
    var name = await findPlace(no);
    if(name != null){
      floor.value = name;
      player.play('audio/scan_book.mp3');
      step.value = 2;
    }else{
      placeNo = null;
    }
  }

  _findBook(no) async {
    var result = await findBook(no);
    if(result.$1 == 200 && result.$2 !=null) {
      bookList.removeWhere((element) => element.no == no);
      bookList.add(result.$2);
      count.value = bookList.length;
      step.value = 3;
    }
  }

  _title(){
    return Container(
        margin: EdgeInsets.only(top: 12.h,bottom: 10.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset("assets/images/up_title.png",width: 60.w,fit: BoxFit.fitWidth,),
            Obx(() => Image.asset("assets/images/up_step$step.png",width: 360.w,fit: BoxFit.fitWidth,)),
            InkWell(
              onTap: (){
                // uhfSerialPortHelper.sendData(stop());
                Get.back();
              },
              child: Image.asset("assets/images/index.png",width: 60.w,fit: BoxFit.fitWidth,)
            )
          ],
        )
    );
  }


  _info(){
    return Container(
      width: double.infinity,
      height: 24.h,
      margin: EdgeInsets.only(bottom: 6.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            children: [
              Image.asset("assets/images/icon_floor.png",width: 8.w,fit: BoxFit.fitWidth,),
              Text(" 层架信息：",style: TextStyle(color: Colors.black,fontSize: 8.sp),),
              Obx(() => Text(floor.value??'',maxLines:2,style: TextStyle(color: Colors.black,fontSize: 8.sp),)),
            ],
          ),
          Container(
            width: 80.w,
            height: 24.h,
            decoration: const BoxDecoration(
              color: Colors.blue,
            ),
            child:  Obx(() => Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(step.value == 4?'上架数量：':'待上架数量：',style: TextStyle(color: Colors.white,fontSize: 8.sp),),
                Text("${count.value}",style: TextStyle(color: Colors.white,fontSize: 8.sp),)
              ],
            )),
          )

        ],
      ),
    );
  }

  _label(){
    return Row(
      children: [
        _labelText('序号',60.w),
        _labelText('条码号',100.w),
        _labelText('书名',200.w),
        _labelText('索书号',100.w),
        _labelText('馆藏状态',60.w),
        // _labelText('存放位置',100.w),
        _labelText('上架状态',80.w),
      ],
    );
  }

  _labelText(text,width){
    return Container(
      width: width,
      height: 24.h,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: Color.fromRGBO(241, 245, 255, 1),
      ),
      child: Text(text,style: TextStyle(color: Colors.black,fontSize: 8.sp),),
    );
  }

  _valueText(text,width,{Color color = Colors.black}){
    return Container(
      width: width,
      height: 24.h,
      alignment: Alignment.center,
      decoration: const BoxDecoration(
        color: Colors.white
      ),
      child: Text(text,style: TextStyle(color: color,fontSize: 8.sp),),
    );
  }

  _scanFloorExample(){
    return SizedBox(
      height: 220.h,
      child: Stack(
        alignment: AlignmentDirectional.center,
        children: [
          Image.asset("assets/images/scan_floor.png",width: 260.w,fit: BoxFit.fitWidth,),
          Positioned(
            top: 100.h,
            right: 0,
            child: Image.asset("assets/images/gun.gif",width: 160.w,fit: BoxFit.fitWidth,),
          ),
          Positioned(
              top: 190.h,
              child: Text("请扫描层架标签",style: TextStyle(color: Colors.blue,fontSize: 12.sp,fontWeight: FontWeight.bold),)
          )

        ],
      )
    );
  }

  _scanBookExample(){
    return SizedBox(
        height: 220.h,
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Image.asset("assets/images/scan_book.png",width: 260.w,fit: BoxFit.fitWidth,),
            Positioned(
              top: 100.h,
              right: 0,
              child: Image.asset("assets/images/gun.gif",width: 160.w,fit: BoxFit.fitWidth,),
            ),
            Positioned(
                top: 190.h,
                child: Text("请扫描层架上的图书",style: TextStyle(color: Colors.blue,fontSize: 12.sp,fontWeight: FontWeight.bold),)
            )
          ],
        )
    );
  }

  _list(){
    return Obx(() => Container(
      height: 180.h,
      margin: EdgeInsets.only(bottom: 10.r),
      child: ListView.separated(
        itemBuilder: (context, index) {
          return _listItem(index);
        },
        itemCount: bookList.length,
        separatorBuilder: (BuildContext context, int index) {
          return const Divider(height: 0.5);
        },
      )
    ));
  }

  _listItem(index){
    var item = bookList[index];
    return Row(
      children: [
        _valueText('${index+1}',60.w),
        _valueText('${item.no}',100.w),
        _valueText('${item.mainTitle}',200.w),
        _valueText('${item.searchNo}',100.w),
        _valueText('${item.stateValue?.replaceAll('in', '在馆').replaceAll('borrowed', '借出')}',60.w),
        // _valueText('${item.placeName}',100.w),
        _valueText(item.stackStatus==0?'待上架':item.stackStatus==1?'已上架':'未上架',80.w,color: Colors.blue),
      ],
    );
  }

  _action(){
    return Obx(() => Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        hasUp.value?
          InkWell(
            onTap: (){
              // uhfSerialPortHelper.sendData(stop());
              Get.back();
            },
            child: Image.asset("assets/images/up_done.png",width: 100.w,fit: BoxFit.fitWidth,),
          ):
          InkWell(
            onTap: (){
              bookList.clear();
              count.value = 0;
              step.value = 2;
              player.play('audio/scan_book.mp3');
            },
            child: Image.asset("assets/images/clear_btn.png",width: 100.w,fit: BoxFit.fitWidth,),
          ),
        SizedBox(width: 60.w,),
        hasUp.value?
          InkWell(
            onTap: ()  {
              floor.value = null;
              placeNo = null;
              count.value = 0;
              bookList.clear();
              hasUp.value = false;
              step.value = 1;
              player.play('audio/scan_place.mp3');

            },
            child: Image.asset("assets/images/up_next.png",width: 100.w,fit: BoxFit.fitWidth,),
          ):
          InkWell(
            onTap: () async {
              var result = await on( bookList.map((element) => element.toJson()).toList(),placeNo);
              for (var item in bookList) {
                var index = bookList.indexOf(item);
                bookList.removeAt(index);
                item.stackStatus = result?1:-1;
                bookList.insert(index, item);
                hasUp.value = true;
              }
              step.value = 4;
              player.play(result?'audio/success.mp3':'audio/failed.mp3');
            },
            child: Image.asset("assets/images/up_btn.png",width: 100.w,fit: BoxFit.fitWidth,),
          ),
      ],
    ));
  }

  _container(){
    return Container(
      width: 620.w,
      height: 310.h,
      padding: EdgeInsets.all(10.w),
      decoration:  BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
        color: Colors.white
      ),
      child: Column(
        children: [
          _info(),
          _label(),
          Obx(() => floor.value == null?_scanFloorExample():count.value == 0?_scanBookExample():_list()),
          Obx(() => Visibility(visible:count.value > 0,child: _action(),))
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.only(left: 10.w,right: 10.w),
        decoration: const BoxDecoration(
          image: DecorationImage(
            fit: BoxFit.fill,
            image: AssetImage(
              "assets/images/bg.png",
            ),
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            _title(),
            _container(),
          ],
        )
      ),
    );
  }
}